<script setup lang="ts">
import { computed } from "vue";
import { BigDecimal } from "@chulei-ui/utils";
import { storeToRefs } from "pinia";
import { NumberUtils } from "../../utils";
import { useMarketStore } from "../../cache/MarketStore";
import { useCacheStore } from "../../sde/cache";
import type { ContractItem } from "../../repositories/contracts/entity";
import { useContract } from "~pages/contracts/use-contract";

const props = defineProps<{
  items: ContractItem[];
  refiningEfficiency?: number;
}>();

const marketStore = useMarketStore();
const cacheStore = useCacheStore();
const { typePrices } = storeToRefs(marketStore);
const { calcTotalPrice } = useContract();
const groupItems = computed(() => {
  return Array.from(
    props.items
      .reduce((map, item) => {
        let counter = map.get(item.type_id!);
        if (!counter) {
          map.set(item.type_id!, BigDecimal.form(0)!);
          counter = map.get(item.type_id!);
        }
        map.set(item.type_id!, counter!.plus(item.quantity));
        return map;
      }, new Map<number, BigDecimal>())
      .entries() ?? []
  );
});

const extra = computed(() => {
  return `预估(${NumberUtils.readableText(calcTotalPrice(props.items, (price) => price.estimate_price))})`;
});
const title = computed(() => {
  return `吉他(${NumberUtils.readableText(calcTotalPrice(props.items, (price) => price.buy_high))})`;
});
defineOptions({
  name: "ContractItems",
});
</script>

<template>
  <el-scrollbar :max-height="300">
    <el-descriptions :title="title" :extra="extra" :column="1" border>
      <el-descriptions-item v-for="[id, quantity] in groupItems" :key="id">
        <template #label>
          {{ cacheStore.getType(id)!.name }}
          <span style="color: var(--el-color-primary)"> X {{ quantity!.toNumber() }}</span>
        </template>
        <div class="flex space-x-1">
          <el-tag v-if="typePrices.get(id)?.estimate_price" type="warning">
            {{
              NumberUtils.readableText(
                BigDecimal.form(quantity)?.multiply(typePrices.get(id)?.estimate_price)?.toFixed(2)?.toNumber()
              )
            }}
            <span v-if="quantity!.toNumber() > 1"
              >({{ NumberUtils.readableText(typePrices.get(id)?.estimate_price) }})</span
            >
          </el-tag>
          <el-tag v-if="typePrices.get(id)?.buy_high" style="color: var(--el-color-primary)">
            {{
              NumberUtils.readableText(
                BigDecimal.form(quantity)?.multiply(typePrices.get(id)?.buy_high)?.toFixed(2)?.toNumber()
              )
            }}
            <span v-if="quantity!.toNumber() > 1">({{ NumberUtils.readableText(typePrices.get(id)?.buy_high) }})</span>
          </el-tag>
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </el-scrollbar>
</template>

<style scoped lang="scss"></style>
